<template>
  <view>
    <!-- 注册面板 -->
    <view class="login-container" v-if="!isLogin">
      <!-- 提示注册的图标 -->
      <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
      <!-- 注册输入框 -->
      <view class="inpit-box">
        <uni-easyinput prefixIcon="person" primaryColor="#fba007" v-model="registerAccount" placeholder="请输入手机号"
          @iconClick="onClick" class="ipt-login"></uni-easyinput>
        <uni-easyinput prefixIcon="locked" primaryColor="#fba007" type="password" v-model="registerPassword"
          placeholder="请输入密码" class="ipt-login"></uni-easyinput>
      </view>
      <!-- 错误提示 -->
      <view class="tips-text">{{registerTipstext}}</view>
      <!-- 注册按钮 -->
      <view class="button-box">
        <button type="primary" class="btn-login" @click="goRegister">注册</button>
      </view>
      <!-- 注册提示 -->
      <view class="login-text" @click="changeMode">已有账号？点击登录</view>
    </view>

    <!-- 登录面板 -->
    <view class="login-container" v-else>
      <!-- 提示登录的图标 -->
      <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
      <!-- 登录输入框 -->
      <view class="inpit-box">
        <uni-easyinput prefixIcon="person" primaryColor="#fba007" v-model="loginAccount" placeholder="请输入账号"
          @iconClick="onClick" class="ipt-login"></uni-easyinput>
        <uni-easyinput prefixIcon="locked" primaryColor="#fba007" type="password" v-model="loginPassword"
          placeholder="请输入密码" class="ipt-login"></uni-easyinput>
      </view>
      <!-- 错误提示 -->
      <view class="tips-text">{{loginTipstext}}</view>
      <!-- 登录按钮 -->
      <view class="button-box">
        <button type="primary" class="btn-login" @click="goLogin">登录</button>
      </view>
      <!-- 登录提示 -->
      <view class="login-text" @click="changeMode">没有账号？点击注册</view>
    </view>

    <!-- 注册授权底部弹出层 -->
    <uni-popup ref="popup" type="bottom" is-mask-click="true">
      <view class="user-form">
        <form @submit="formSubmit">
          <view class="prompt">申请获取您的头像、昵称</view>

          <view class="get_user">
            <view class="user-view">头像：
              <button class="avatar_btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                <image class="user-img" :src="avatarUrl" mode="aspectFill" />
              </button>
            </view>
            <view class="user-view">昵称：
              <input class="user-name" name="nickName" type="nickname" placeholder="请输入昵称" />
            </view>
          </view>

          <view class="popup-button">
            <button class="refuse-btn" form-type="reset" @click="closePopup">拒绝</button>
            <button class="allow-btn" form-type="submit" type="primary">允许</button>
          </view>
        </form>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import {
    mapMutations
  } from 'vuex'
  const defaultAvatarUrl =
    'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
  export default {
    data() {
      return {
        // 注册的账号密码
        registerAccount: '',
        registerPassword: '',
        // 登录的账号密码
        loginAccount: '',
        loginPassword: '',
        // 注册提示语
        registerTipstext: '',
        // 登录提示语
        loginTipstext: '',
        // 账号正确性
        isAccountCorrect: false,
        // 密码正确性
        isPasswordCorrect: false,
        // 登录或者注册
        isLogin: true,
        // 弹出层信息
        avatarUrl: defaultAvatarUrl,
        userName: '',
      };
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateUserClockInList', 'updateUserPlanList',
        'updateUserRecordList', 'updateUserVideoList', 'updateUserArticleList', 'updateUserTrendList', 'updateUserLikeTrendList'
      ]),
      ...mapMutations('m_music', ['setUserMusicList']),
      ...mapMutations('m_cart', ['updateUserCartList']),
      // 变化登录注册模式
      changeMode() {
        if (this.isLogin) {
          this.isLogin = false
          this.registerAccount = ''
          this.registerPassword = ''
          this.loginAccount = ''
          this.loginPassword = ''
        } else {
          this.isLogin = true
          this.registerAccount = ''
          this.registerPassword = ''
          this.loginAccount = ''
          this.loginPassword = ''
        }
      },
      // 注册
      goRegister() {
        console.log(this.registerAccount)
        console.log(this.registerPassword)

        if (this.registerAccount === '') {
          this.registerTipstext = '请输入手机号'
        } else {
          // 对账号(手机号)的格式进行验证
          const mobileRegex = /^(\+?0?86-?)?1[3-9]\d{9}$/;
          if (!mobileRegex.test(this.registerAccount)) {
            console.log('手机号格式不正确！');
            this.registerTipstext = '手机号输入错误'
          } else {
            this.isAccountCorrect = true
          }
        }

        // 如果账号正确，则判断密码正确性
        if (this.isAccountCorrect === true) {
          if (this.registerPassword === '') {
            this.registerTipstext = '请输入密码'
          } else {
            if (this.registerPassword.length < 8) {
              this.registerTipstext = '密码至少8位数，且由数字+字母+特殊字符组成'
            } else {
              // 对密码格式进行验证
              const passwordRegex = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,}$/;
              if (!passwordRegex.test(this.registerPassword)) {
                console.log('密码格式不正确');
                this.registerTipstext = '密码需由数字+字母+特殊字符组成'
              } else {
                this.isPasswordCorrect = true
                this.registerTipstext = ''
              }
            }
          }
        }
        if (this.isAccountCorrect === true && this.isPasswordCorrect === true) {
          // 发送注册验证
          this.registerVerify()
        }
      },

      // 发送注册验证
      async registerVerify() {
        const [err, res] = await uni.login().catch(err => err)
        if (err || res.errMsg !== 'login:ok') return uni.$showMsg('注册失败！')
        // 准备参数
        const query = {
          code: res.code,
          account: this.registerAccount,
          password: this.registerPassword,
        }
        try {
          const response = await uni.$http.post('/api/register', query);
          const res = response.data;
          if (res.meta.status === 200) {
            this.isLogin = true
            return uni.$showMsg('注册成功');
          }
          if (res.meta.status === 400) return uni.$showMsg('该账号已被注册');
          if (res.meta.status !== 200 && res.meta.status !== 400 && res.meta.status !== 404) return uni.$showMsg(
            '注册失败');
          if (res.meta.status === 404) {
            this.openPopup()
          }
        } catch (error) {
          console.error(error);
          uni.$showMsg('请求失败');
        }
      },

      // 创建新用户
      async createNewUser() {
        const [err, res] = await uni.login().catch(err => err)
        if (err || res.errMsg !== 'login:ok') return uni.$showMsg('注册失败！')
        // 准备参数
        const query = {
          code: res.code,
          account: this.registerAccount,
          password: this.registerPassword,
          userName: this.userName,
        }
        const {
          data: createResult
        } = await uni.$http.post('/api/createNewUser', query)
        if (createResult.meta.status === 404) {
          return uni.$showMsg('注册失败！')
        } else if (createResult.meta.status === 200) {
          this.uploadAvatarToServer(createResult.message.userID)
          this.isLogin = true
          return uni.$showMsg('注册成功')
        }
      },

      // 申请获取用户信息，打开底部弹出层
      openPopup() {
        this.$refs.popup.open()
      },
      // popup弹窗点击"允许"按钮触发提交事件函数
      formSubmit(e) {
        let nickName = e.detail.value.nickName
        if (this.avatarUrl === defaultAvatarUrl) {
          return uni.$showMsg('请选择头像！')
        } else if (!nickName) {
          return uni.$showMsg('请输入昵称！')
        } else {
          this.userName = nickName
          this.createNewUser()
          this.$refs.popup.close()
        }
      },
      // popup弹窗点击"拒绝"按钮关闭popup弹窗
      closePopup() {
        this.$refs.popup.close()
        this.avatarUrl = defaultAvatarUrl
      },
      // 获取用户头像
      onChooseAvatar(e) {
        console.log(e.detail)
        const {
          avatarUrl
        } = e.detail
        this.avatarUrl = avatarUrl
      },
      // 上传头像到服务器中
      uploadAvatarToServer(ID) {
        const userID = ID
        console.log('上传头像')
        uni.uploadFile({
          filePath: this.avatarUrl,
          name: 'image',
          url: 'https://jeoz.top:3000/api/uploadAvatar?userID=' + userID,
          success: res => {
            console.log('上传成功')
          }
        })
      },

      // 登录
      async goLogin() {
        if (this.loginAccount === '') {
          this.loginTipstext = '请输入账号'
          return
        } else if (this.loginPassword === '') {
          this.loginTipstext = '请输入密码'
          return
        } else if (this.loginAccount !== '' && this.loginPassword !== '') {
          this.loginTipstext = ''
        }
        const [err, res] = await uni.login().catch(err => err)
        if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
        // 准备参数
        const query = {
          code: res.code,
          account: this.loginAccount,
          password: this.loginPassword,
        }
        const {
          data: loginResult
        } = await uni.$http.post('/api/login', query)
        if (loginResult.meta.status === 400) {
          return uni.$showMsg('账号未注册！')
        } else if (loginResult.meta.status === 404) {
          return uni.$showMsg('密码错误')
        } else if (loginResult.meta.status === 200) {
          this.updateToken(loginResult.message.token)
          //获取用户信息后更新userInfo
          this.updateUserInfo(loginResult.message.userInfo)
          // 获取用户所有的信息资料
          this.getUserInformation()
          // 返回上一页
          uni.navigateBack({
            delta: 1,
          });
          return uni.$showMsg('登录成功')
        } else {
          return uni.$showMsg('登录失败')
        }
      },

      // 获取用户所有信息资料
      async getUserInformation() {
        var token = uni.getStorageSync('token')
        // 调用获取用户所有信息资料
        const {
          data: res
        } = await uni.$http.get('/api/get/userInformation?token=' + token)
        console.log(res.message)
        this.updateUserClockInList(res.message.clockinList)
        this.updateUserPlanList(res.message.planList)
        this.updateUserRecordList(res.message.recordList)
        this.updateUserVideoList(res.message.videoList)
        this.updateUserArticleList(res.message.articleList)
        this.updateUserCartList(res.message.cartList)
        this.updateUserTrendList(res.message.trendList)
        this.updateUserLikeTrendList(res.message.likeTrendList)
        this.setUserMusicList(res.message.musicList)
      },
    },
  }
</script>

<style lang="scss">
  page {
    background-color: white;
  }

  .login-container {
    // 登录盒子的样式
    height: 750rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
    position: relative;

    // 绘制登录盒子底部的半椭圆造型
    &::after {
      content: '';
      display: block;
      position: absolute;
      width: 100%;
      height: 40px;
      bottom: 0;
      left: 0;
      background-color: white;
      border-radius: 100%;
      transform: translateY(50%); // 向下移动自身50%的距离
    }

    .inpit-box {
      width: 90%;

      // border: 1px solid red;
      .ipt-login {}
    }

    .button-box {
      width: 90%;

      // border: 1px solid red;
      .btn-login {
        //登录按钮的样式
        border-radius: 100px;
        margin: 15px 0;
        background-color: #fba007;
      }

      .btn-login:first-child {
        margin-top: 0;
      }

    }

    .tips-text {
      //按钮下方提示消息的样式
      font-size: 12px;
      color: red;
      margin: 15rpx 0;
    }

    .login-text {
      font-size: 12px;
      color: gray;
    }
  }

  // uni-popup
  .user-form {
    height: 190px;
    background: white;
    border-top-left-radius: 30rpx;
    border-top-right-radius: 30rpx;
    padding-top: 18px;

    .prompt {
      // border: 1rpx solid black;
      font-size: 30rpx;
      font-weight: bolder;
      margin-left: 30rpx;
    }

    .get_user {
      .user-view {
        // border: 1rpx solid black;
        height: 100rpx;
        display: flex;
        align-items: center;
        color: gray;
        font-size: 28rpx;
        border-bottom: 1px solid #ddd;
        margin-left: 30rpx;
        margin-right: 30rpx;

        .avatar_btn {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          background-color: transparent;
          padding: 0;
          margin-right: 20rpx;
          line-height: 1.3;
        }

        ::after {
          border: none;
          border-radius: 0;
        }

        .user-img {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
        }

        .user-name {
          flex: 1;
          text-align: right;
          font-size: 28rpx;
          color: black;
          // border: 1rpx solid gray;
          border-radius: 10rpx;
          padding-right: 24rpx;
        }
      }
    }

    .popup-button {
      width: 440rpx;
      margin: 15px auto;
      display: flex;


      // border: 1rpx solid black; 
      /* padding: 0; */
      .refuse-btn {
        width: 200rpx;
        height: 70rpx;
        line-height: 70rpx;
        margin: 0;
        /* align-items: center;
            justify-content: center; */
        color: black;
        font-size: 28rpx;
        border-radius: 100px;
        background-color: #eee;
      }

      ::after {
        border: none;
      }

      .allow-btn {
        width: 200rpx;
        height: 70rpx;
        line-height: 70rpx;
        font-size: 28rpx;
        /* align-items: center; */
        /* justify-content: center; */
        /* display: flex; */
        margin-left: 40rpx;
        border-radius: 100px;
        background-color: #fba007;
      }
    }
  }
</style>